_package("caf.ui");

_import("caf.mui.Component");
_import("caf.mui.Pane");

/**
 * 支持从模板创建的面板组件
 */
_class("TplPane", Pane, function(){
	this._init = function(){
		_super._init.call(this);
		this._tpl = "";  //对应的模板文件名
		/*
		this._tags = {
			"scrollview": ScrollView
		};
		*/
		this._components = {};  //根据自定义标签库创建的组件
	};
	this.init = function(obj){
		_super.init.apply(this, arguments);
	};
	this.dispose = function(){
		for(var k in this._components){
			//this["m_" + k] = null;
			this._components[k].dispose();
			delete this._components[k];
		}
		_super.dispose.apply(this);
	};
	this.getTpl = function(v){
		return this._tpl;
	};
	this.setTpl = function(v){
		this._tpl = v;
	};
	/*
	this.renderTag = function(obj){
		var nodes = obj.childNodes;
		for(var i = 0, len = nodes.length; i < len; i++){
			var node = nodes[i];
			if(node.nodeType == 1){
				var tag = node.getAttribute("_tag");
				if(tag && tag in this._tags){
					var component = new this._tags[tag]();
					component.bind(node);
				}
				if(node.hasChildNodes()){
					this.renderTag(node);
				}
			}
			node = null;
		}
		nodes = null;
	};
	*/
	/**
	 * _tag属性的结构: "a:{tagname} {id} {model} {pageSize} {itemClass} {key}"
	 */
	this.parseTag = function(str){
		var conf = {};
		var arr = str.split(" ");
		for(var i = 0, len = arr.length; i < len; i++){
			var a = arr[i].split("=");
			switch(a[0]){
			case "model"    : conf[a[0]] = this._app.getModel(a[1]);break;
			case "pageSize" : conf[a[0]] = parseInt(a[1], 10);break;
			case "itemClass": conf[a[0]] = __context__[a[1]];break;
			default         : conf[a[0]] = a[1];break;
			}
		}
		return conf;
	};
	this._toArray = function(nodes){
		var arr = [];
		for(var i = 0, len = nodes.length; i < len; i++){
			arr.push(nodes[i]);
		}
		return arr;
	};
	/**
	 * 初始化Page内部的组件
	 */
	this.initComponents = function(){
		var tags = ["div", "ul", "a"];
		for(var i = 0, len = tags.length; i < len; i++){
			var tag = tags[i];
			var nodes = this._toArray(this._self.getElementsByTagName(tag));
			for(var j = 0, len1 = nodes.length; j < len1; j++){
				var node = nodes[j];
				if(node._ptr && node._ptr instanceof Component) continue;
				var tag1 = node.getAttribute("_tag");
				if(tag1){
					var conf = this.parseTag(tag1);
					conf["parent"] = this;
					var clazz = this._app.getTagClass(conf.tag);  //tagname
					var component = new clazz();
					component.bind(node, conf);
					//this["m_" + conf.id] = component;
					this._components[conf.id] = component;  //注册组件
				}
				node = null;
			}
			nodes = null;
		}
	};
	this.cc =  //别名
	this.getComponent = function(id){
		return this._components[id];
	};
	this.findComponent = function(id){
		for(var k in this._components){
			if(k.indexOf(id) != -1){
				return this._components[k];
			}
		}
		return null;
	};
});